package com.novax.ex.activity.provider.controller.inner;

import com.novax.ex.activity.infrastructure.entity.OperationV2Config;
import com.novax.ex.activity.infrastructure.entity.OperationV2SubConfig;
import com.novax.ex.activity.open.api.inner.OperationV2ConfigApi;
import com.novax.ex.activity.open.model.query.OperationV2ConfigQuery;
import com.novax.ex.activity.open.model.request.OperationV2ConfigRequest;
import com.novax.ex.activity.open.model.response.OperationUserLogOuterResponse;
import com.novax.ex.activity.open.model.response.OperationV2ConfigResponse;
import com.novax.ex.activity.provider.controller.BaseActivityController;
import com.novax.ex.activity.provider.service.OperationV2ConfigService;
import com.novax.ex.activity.provider.service.OperationV2RuleService;
import com.novax.ex.activity.provider.service.OperationV2SubConfigService;
import com.novax.ex.activity.provider.service.OperationV2UserLogService;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.enums.LanguageType;
import com.novax.ex.common.enums.OperationStatus;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.CopyUtils;
import com.novax.ex.common.util.PageUtil;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @Description 活动落地页配置V2
 * @Author ChenXi
 * @Date 2023/04/18/10:08
 */

@RestController
public class OperationV2ConfigController extends BaseActivityController implements OperationV2ConfigApi {

    @Resource
    private OperationV2ConfigService operationV2ConfigService;
    @Resource
    private OperationV2SubConfigService operationV2SubConfigService;
    @Resource
    private OperationV2RuleService operationV2RuleService;
    @Resource
    private OperationV2UserLogService operationV2UserLogService;

    @Override
    public ReturnResult<PageUtil<OperationV2ConfigResponse>> page( OperationV2ConfigQuery query) {
        PageUtil<OperationV2ConfigResponse> pageInfo = new PageUtil<>(query);
        pageInfo.setCondition(Collections.singletonMap("query", query));
        operationV2ConfigService.findPage(pageInfo, OperationV2ConfigResponse.class);
        return ReturnResult.success(pageInfo);
    }

    @Override
    public ReturnResult<?> add(String language, OperationV2ConfigRequest operationConfigRequest, BindingResult bindingResult) {
        // 缺少必填项
        if(bindingResult.hasErrors()){
            return ReturnResult.fail(getInternational(language, InternationalCode.LACK_VALUE));
        }
        OperationV2Config operationV2Config = CopyUtils.copyObject(operationConfigRequest, OperationV2Config.class);
        operationV2Config.setCustomId(getCustomId());
        operationV2Config.setState(OperationStatus.close.getType());
        boolean res = operationV2ConfigService.addSelective(operationV2Config);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<?> modify(String language, Long operationId, OperationV2ConfigRequest operationConfigRequest,
                                  BindingResult bindingResult) {
        // 缺少必填项
        if(bindingResult.hasErrors()){
            return ReturnResult.fail(getInternational(language, InternationalCode.LACK_VALUE));
        }
        OperationV2Config operationV2Config = CopyUtils.copyObject(operationConfigRequest, OperationV2Config.class);
        operationV2Config.setId(operationId);
        String name = operationV2Config.getName();
        // 为空也正常修改
        if(name  == null || name.isEmpty()){
            operationV2Config.setName(" ");
        }

        // 如果是开启活动则必须得有配置至少一个子活动且有英文活动标题与规则
        if(operationV2Config.getState().equals(OperationStatus.open.getType())){
            // 主活动 多语言配置
            if(operationV2RuleService.queryOperationIdAndLanguage(operationId, LanguageType.en.getType()) <= 0){
                return ReturnResult.fail("多语言至少已配置英文");
            }

            // 至少有一个子活动开启中
            List<OperationV2SubConfig> subConfigList = operationV2SubConfigService.queryOpenList(operationId);
            if(subConfigList.isEmpty()){
                return ReturnResult.fail("至少需要一个子活动开启中");
            }

        }
        boolean res = operationV2ConfigService.modifySelective(operationV2Config);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<?> remove(String language, Long operationId) {
        OperationV2Config operationV2Config = operationV2ConfigService.find(operationId);
        if(Objects.isNull(operationV2Config)){
            return ReturnResult.fail(getInternational(language, InternationalCode.NOT_FOUND));
        }
        if (OperationStatus.open.getType().equals(operationV2Config.getState())){
            return ReturnResult.fail(getInternational(language, InternationalCode.ACTIVITY_STATUS));
        }
        boolean res = operationV2ConfigService.remove(operationId);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<List<OperationUserLogOuterResponse>> queryList(Long id) {
        return ReturnResult.success(CopyUtils.copyList(operationV2UserLogService.queryList(id), OperationUserLogOuterResponse.class));
    }

    /***
     * @Description: 生成自定义id
     * @Author: ChenXi
     * @Date:  2023/4/18 15:34
     * @param
     * @return: java.lang.String
     **/
    private String getCustomId() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();
        Random random = new Random();

        // 是否唯一
        boolean isUnique = false;

        while (!isUnique) {
            result.setLength(0);
            result.append("BM");
            for (int i = 0; i < 4; i++) {
                int index = random.nextInt(characters.length());
                result.append(characters.charAt(index));
            }
            Long count = operationV2ConfigService.findByCustomId(result.toString());
            isUnique = (count == 0);
        }

        return result.toString();
    }

}
